let _Vue = null;
export default class VueRouter {

  // 通过Vue.use(VueRouter)启用VueRouter，Vue.use会调用传入的对象下的install方法
  static install(Vue) {
    if (VueRouter.install.installed && _Vue === Vue) return;
    VueRouter.install.installed = true;
    _Vue = Vue;
    Vue.mixin({
      beforeCreate () {
        // 挂载的动作只需要执行一次，如果是组件的话就不执行了，如果是Vue实例就需要执行（组件属性没有route,实例中有）
        if (this.$options.router) {
          this._router = this.$options.router;
          this._routerRoot = this;
        } else {
          this._routerRoot = this.$parent && this.$parent._router
        }
      }
    })
  }


  constructor(options = {}) {
    this.options = options;
    this.mode = options.mode || 'hash'
    // 记录路由地址与路由组件的关系
    this.routeMap = {};
    this.data = _Vue.observable({
      current: '/'
    })
    this.init()
  }

  init() {
    this.initRouteMap();
    this.initEvents()
  }

  initRouteMap() {
    this.options.routes.forEach(route => {
      this.routeMap[route.path] = route.component
    })
  }

  initEvents() {
    if (this.mode === 'hash') {
      window.addEventListener('hashchange', () => {
        this.data.current = location.hash.substr(1)
      })
    } else {
      window.addEventListener('popstate', () => {
        this.data.current = window.location.pathname
      })
    }
  }


  // 实现router-link 和 router-view 组件
  initComponents() {
    let self = this
    _Vue.component('route-link', {
      props: {
        to: String
      },
      render(h) {
        return h('a', {
          attrs: {
            href: this.to
          },
          on: {
            click: this.clickHandler
          }
        })
      },
      methods: {
        clickHandler(e) {
          if (self.mode === 'hash') {
            window.location.hash = `#${this.to}`
          } else {
            history.pushState({}, '', this.to)
          }
          this.$router.data.current = this.to;
          e.preventDefault();
        }
      }
    })

    
    _Vue.component('router-view', {
        render (h) {
          // 根据当前路径找到对应的组件，注意 this 的问题
            const component = self.routeMap[self.data.current]
            return h(component)
        }
    })
  }

  
  
}